package com.siashan.unipay4j.wx.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.PayChannel;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.UnipayConst;
import com.siashan.unipay4j.core.pay.IPayment;
import com.siashan.unipay4j.core.pay.PayModel;
import com.siashan.unipay4j.core.util.EnumUtil;
import com.siashan.unipay4j.core.util.MoneyUtil;
import com.siashan.unipay4j.core.util.StrUtil;
import com.siashan.unipay4j.wx.AbstractWxPay;
import com.siashan.unipay4j.wx.CurrencyEnum;
import com.siashan.unipay4j.wx.WxPayVersionEnum;
import com.siashan.unipay4j.wx.model.Amount;
import com.siashan.unipay4j.wx.model.Payer;
import com.siashan.unipay4j.wx.model.UnifiedOrderModel;
import com.siashan.unipay4j.wx.sdk.WXPayConstants;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

import static org.apache.http.HttpStatus.SC_MULTIPLE_CHOICES;
import static org.apache.http.HttpStatus.SC_OK;

/**
 * 微信支付抽象类
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public abstract class WxPay extends AbstractWxPay implements IPayment {
    public WxPay() {
    }

    public WxPay(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 封装支付请求参数
     *
     * @param model 支付请求参数
     * @param tradeType 交易类型
     *
     * @return 支付请求参数
     */
    protected HashMap<String, String> wapperPayRequestData(PayModel model, WxTradeTypeEnum tradeType) {
        HashMap<String, String> data = new HashMap<String, String>(8);
        // 商品描述
        data.put("body", model.getBody());
        // 商户订单号
        data.put("out_trade_no", model.getOutTradeNo());
        // 币种
        data.put("fee_type", CurrencyEnum.CNY.getValue());
        // 支付金额
        String amount = String.valueOf(MoneyUtil.yuan2Cent(model.getPrice()));
        data.put("total_fee", amount);
        // 乘客终端IP
        data.put("spbill_create_ip", model.getSpbillCreateIp());
        // 交易类型  付款码支付无需传递
        if (!WxTradeTypeEnum.MICROPAY.equals(tradeType)) {
            data.put("trade_type", tradeType.getValue());
        }
        // 付款码
        if (WxTradeTypeEnum.MICROPAY.equals(tradeType)) {
            data.put("auth_code", model.getAuthCode());
        }
        // 用户标识
        if (needOpenId()) {
            data.put("openid", model.getOpenid());
        }
        // 分账标识
        data.put("profit_sharing", model.getProfitSharing().getValue());
        // 回调地址
        data.put("notify_url", model.getNotifyUrl());
        return data;
    }

    /**
     * 封装支付请求参数
     *
     * @param model 支付请求参数
     * @since 2.0.1
     * @return 统一下单实体类
     */
    protected UnifiedOrderModel wapperUnifiedOrderModel(PayModel model) {
        UnifiedOrderModel orderModel = new UnifiedOrderModel();
        // 商品描述
        orderModel.setDescription(model.getBody());
        // 商户订单号
        orderModel.setOutTradeNo(model.getOutTradeNo());
        // 回调地址
        if (StrUtil.isNotEmpty(model.getNotifyUrl())){
            orderModel.setNotifyUrl(model.getNotifyUrl());
        }else{
            orderModel.setNotifyUrl(wxPayConfig.getNotifyurl());
        }
        // 支付金额
        Amount amount = new Amount();
        amount.setTotal(MoneyUtil.yuan2Cent(model.getPrice()));
        amount.setCurrency(CurrencyEnum.CNY.getValue());
        orderModel.setAmount(amount);
        // 用户标识
        if (needOpenId()) {
            Payer payer = new Payer();
            payer.setOpenid(model.getOpenid());
            orderModel.setPayer(payer);
        }
        orderModel.setAppid(wxPayConfig.getAppId());
        orderModel.setMchid(wxPayConfig.getMchId());
        return orderModel;
    }

    /**
     * 执行支付请求
     *
     * @param model       支付请求参数
     * @param tradeType   交易类型
     * @return 支付请求结果
     */
    protected Result doPay(PayModel model, WxTradeTypeEnum tradeType) {
        WxPayVersionEnum ver = EnumUtil.getIEnum(WxPayVersionEnum.class, wxPayConfig.getVersion());
        Result result = null;
        switch (ver) {
            case V2:
                result = doPayV2(model, tradeType);
                break;
            case V3:
                result = doPayV3(model, tradeType);
                break;
            default:
                break;
        }
        return result;
    }


    /**
     * v2版本执行支付请求
     *
     * @param model       支付请求参数
     * @param tradeType   交易类型
     * @return 支付请求结果
     *
     * @since 2.0.1
     */
    private Result doPayV2(PayModel model, WxTradeTypeEnum tradeType) {
        String outTransNo = model.getOutTradeNo();
        log.info("WxPay::{}=>订单{} 支付请求到达", tradeType, outTransNo);
        HashMap<String, String> data = wapperPayRequestData(model, tradeType);
        try {
            Map<String, String> r = initWxPay().unifiedOrder(data);
            log.info("WxPay::{}=>订单{} 下单返回报文:{}", tradeType, outTransNo, r);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                if (UnipayConst.SUCCESS.equals(r.get(WXPayConstants.RESULT_CODE))) {
                    log.info("WxPay::{}=>订单{} 下单成功", tradeType, outTransNo);
                    return doTradeSuccess(r);
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxPay::{}=>订单{} 下单失败,错误代码:{},错误描述:{}", tradeType, outTransNo, errCode, errCodeDes);
                    return Result.tradeFail(errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxPay::{}=>订单{} 下单失败,错误代码:{},错误描述:{}", tradeType, outTransNo, returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }
        } catch (Exception e) {
            log.warn("WxPay::{}=>订单{} 下单时发生异常", tradeType, outTransNo, e);
        }
        return Result.exception();
    }


    /**
     * v3版本执行支付请求
     *
     * @param model       支付请求参数
     * @param tradeType   交易类型
     * @return 支付请求结果
     *
     * @since 2.0.1
     */

    public Result doPayV3(PayModel model, WxTradeTypeEnum tradeType) {
        String outTransNo = model.getOutTradeNo();
        log.info("WxPay::{}=>订单{} 支付请求到达", tradeType, outTransNo);
        UnifiedOrderModel orderModel = wapperUnifiedOrderModel(model);
        WechatPayHttpClientBuilder builder = loadBuilder();
        // ... 接下来，你仍然可以通过builder设置各种参数，来配置你的HttpClient
        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签
        CloseableHttpClient httpClient = builder.build();
        HttpPost httpPost = initHttpPost(loadV3PayUrl(), JSON.toJSONString(orderModel));
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            String body = EntityUtils.toString(response.getEntity());
            log.info("WxPay::{}=>订单{} 下单返回报文:{}", tradeType, outTransNo, body);
            if (statusLine.getStatusCode() >= SC_OK && statusLine.getStatusCode() < SC_MULTIPLE_CHOICES) {
                log.info("WxPay::{}=>订单{} 下单成功", tradeType, outTransNo);
                return doTradeSuccessV3(body,orderModel);
            } else {
                JSONObject bodyJson = JSON.parseObject(body);
                String errCode = bodyJson.getString(WXPayConstants.CODE);
                String errCodeDes = bodyJson.getString(WXPayConstants.MESSAGE);
                log.info("WxPay::{}=>订单{} 下单失败,错误代码:{},错误描述:{}", tradeType, outTransNo, errCode, errCodeDes);
                return Result.tradeFail(errCode, errCodeDes);
            }
        } catch (Exception e) {
            log.warn("WxPay::{}=>订单{} 下单时发生异常", tradeType, outTransNo, e);
        }
        return Result.exception();
    }

    /**
     * 加载V3支付请求地址
     * @return 支付请求地址
     */
    public abstract String loadV3PayUrl();

    /**
     * 是否需要openId参数
     *
     * @return 是否需要
     */
    public abstract boolean needOpenId();


    /**
     * 处理交易成功逻辑
     *
     * @param r  报文
     * @return 返回结果
     * @throws Exception
     */
    public abstract Result doTradeSuccess(Map<String, String> r) throws Exception;

    /**
     * 处理交易成功逻辑
     *
     * @param body  报文
     * @param orderModel 下单请求参数
     * @return 返回结果
     */
    public abstract Result doTradeSuccessV3(String body,UnifiedOrderModel orderModel) ;





    public static void main(String[] args) {
        log.info("WxPay::{}=>订单{} 支付请求到达", WxTradeTypeEnum.APP, "123456");
    }

}
